//
//  ChatViewController.m
//  ChatDemo
//
//  Created by 陈石 on 15/5/12.
//  Copyright (c) 2015年 陈石. All rights reserved.
//

@import AVFoundation;

#import "ChatViewController.h"
#import "MessageCell.h"
#import "AppDelegate.h"
#import "MessageManager.h"

@interface ChatViewController () <UITableViewDataSource, UITableViewDelegate, sendContentDelegate, MessageCellDelegate>
{
    MessageManager *messageManager;
    AppDelegate    *appDelegate;
}

@property(weak, nonatomic) IBOutlet UITableView        *ChatTableView;
@property(weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@end

@implementation ChatViewController
@synthesize contact;
@synthesize messages;

static NSString *previousTime = nil;

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Back-Small.png"] style:UIBarButtonItemStylePlain target:self action:@selector(didClickBackAction)];
    self.navigationItem.leftBarButtonItem = backButtonItem;
    self.view.backgroundColor             = [UIColor whiteColor];
    messageManager = [MessageManager new];
    appDelegate    = (AppDelegate *) [[UIApplication sharedApplication] delegate];
    [self loadBaseViewsAndData];

    [self initBackButton];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];

    self.ChatTableView.frame  = CGRectMake(0, 21, self.view.frame.size.width, self.view.frame.size.height - 40);
    _ChatTableView.dataSource = self;
    _ChatTableView.delegate   = self;

    //添加输入框随键盘升起降落坐标改变事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tableViewScrollToBottom) name:UIKeyboardDidShowNotification object:nil];
}

#pragma - mark keyboardNotification

- (void)keyboardChange:(NSNotification *)notification
{
    NSDictionary         *userInfo = [notification userInfo];
    NSTimeInterval       animationDuration;
    UIViewAnimationCurve animationCurve;
    CGRect               keyboardEndFrame;

    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];

    if (notification.name == UIKeyboardWillShowNotification)
    {
        self.bottomConstraint.constant = keyboardEndFrame.size.height + 40;
    }
    else
    {
        self.bottomConstraint.constant = 40;
    }

    [self.view layoutIfNeeded];

    CGRect newFrame = self.sendcontentview.frame;
    newFrame.origin.y          = keyboardEndFrame.origin.y - 64 - newFrame.size.height;
    self.sendcontentview.frame = newFrame;

    [UIView commitAnimations];
}

- (void)tableViewScrollToBottom
{

    if (messages.count == 0)
    {
        return;
    }

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:messages.count - 1 inSection:0];
    [self.ChatTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark - tableView delegate & datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    MessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    if (cell == nil)
    {
        cell = [[MessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"];
        cell.delegate = self;
    }

    [cell setMessageFrame:messages[indexPath.row]];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [messages[indexPath.row] cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.view endEditing:YES];
}

#pragma - mark SendContentDelegate

- (void)sendMessage:(SendContentView *)sencontentView Message:(NSString *)message
{
    [self setTextFieldAndButtonState:sencontentView];

    NSMutableDictionary *dMessage = [NSMutableDictionary new];
    dMessage[@"userName"]    = contact[@"userName"];
    dMessage[@"message"]     = message;
    dMessage[@"messageType"] = @"Text";
    ResultSet *rs = [messageManager sendMessage:dMessage];

    if ([self verifyResutSet:rs])
    {
        [messages removeAllObjects];
        rs = [messageManager receiveMessage:self.contact[@"userName"]];
        messages.array = [self setMessageAndFrame:[rs toArray]];
    }

    [self.ChatTableView reloadData];
    [self tableViewScrollToBottom];
}

- (void)sendImage:(SendContentView *)sencontentView Message:(UIImage *)image
{
    [self setTextFieldAndButtonState:sencontentView];

    NSMutableDictionary *dMessage = [NSMutableDictionary new];
    dMessage[@"userName"]    = contact[@"userName"];
    dMessage[@"image"]       = image;
    dMessage[@"messageType"] = @"Image";
    ResultSet *rs = [messageManager sendMessage:dMessage];

    if ([self verifyResutSet:rs])
    {
        [messages removeAllObjects];
        rs = [messageManager receiveMessage:self.contact[@"userName"]];
        messages.array = [self setMessageAndFrame:[rs toArray]];
    }

    [self.ChatTableView reloadData];
    [self tableViewScrollToBottom];
}

- (void)sendAudio:(SendContentView *)sencontentView Message:(NSData *)audio time:(NSInteger)second;
{
    [self setTextFieldAndButtonState:sencontentView];

    NSMutableDictionary *dMessage = [NSMutableDictionary new];
    dMessage[@"userName"]    = contact[@"userName"];
    dMessage[@"audio"]       = audio;
    dMessage[@"messageType"] = @"Audio";
    ResultSet *rs = [messageManager sendMessage:dMessage];

    if ([self verifyResutSet:rs])
    {
        [messages removeAllObjects];
        rs = [messageManager receiveMessage:self.contact[@"userName"]];
        messages.array = [self setMessageAndFrame:[rs toArray]];
    }

    [self.ChatTableView reloadData];
    [self tableViewScrollToBottom];
}

- (void)sendMedia:(SendContentView *)sencontentView Message:(NSData *)media
{
}

- (void)setTextFieldAndButtonState:(SendContentView *)sencontentView
{
    sencontentView.TextViewInput.text = @"";
    [sencontentView changeSendBtnWithPhoto:YES];
}

#pragma - mark LoadData

- (void)loadBaseViewsAndData
{
    _sendcontentview = [[SendContentView alloc] initWithSuperVC:self];
    _sendcontentview.delegate = self;

    messages = [[NSMutableArray alloc] init];
    self.title = self.contact[@"alias"];
    ResultSet *rs = [messageManager receiveMessage:self.contact[@"userName"]];

    if ([self verifyResutSet:rs])
    {
        if (![rs isEmpty])
        {
            messages.array = [self setMessageAndFrame:[rs toArray]];
        }
    }

    [self.view addSubview:_sendcontentview];
    [self.ChatTableView reloadData];
    [self tableViewScrollToBottom];
}

//通过数据源返回messageFrame类型数据源
- (NSArray *)setMessageAndFrame:(NSArray *)arr
{
    NSMutableArray *result    = [NSMutableArray array];
    NSNumber       *contactID = contact[@"id"];

    for (int i = 0; i < arr.count; i++)
    {
        NSMutableDictionary *Msg          = [NSMutableDictionary dictionaryWithDictionary:arr[i]];
        NSNumber            *toContactID  = Msg[@"toContact"][@"id"];
        MessageFrame        *messageFrame = [[MessageFrame alloc] init];
        Message             *message      = [[Message alloc] init];

        if ([contactID isEqualToNumber:toContactID])
        {
            [message SetMsgWithDict:Msg MessageFrom:MessageFromMe];
        }
        else
        {
            [message SetMsgWithDict:Msg MessageFrom:MessageFromOther];
        }

        [messageFrame setMessage:message];

        [result addObject:messageFrame];
    }
    return result;
}

#pragma mark - cellDelegate

- (void)headImageDidClick:(MessageCell *)cell userId:(NSString *)userId
{
    // headIamgeIcon is clicked
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:cell.messageFrame.message.strName message:@"headImage clicked" delegate:nil cancelButtonTitle:@"sure" otherButtonTitles:nil];
    [alert show];
}

- (void)didClickBackAction
{
    [self.view endEditing:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
